<?php

include '../inc/util.php';
//include 'inc/config.php';

define("UPLOAD_DIR", "../upload/");
define("ANNOUNCE_DIR", "../upload/announce/");
define("TASK_DIR", "../upload/task/");

$upload_path = UPLOAD_DIR . basename($_FILES['uploadedfile']['name']);
$announce_path = ANNOUNCE_DIR . basename($_FILES['uploadedfile']['name']);
$task_path = TASK_DIR . basename($_FILES['uploadedfile']['name']);

$response = array();

if ($_GET['action'] == "upload") {
    if (move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $upload_path)) {
        echo baseUrl() . str_replace('../', '', $upload_path);
    } else {
        $response['status'] = "Error";
        $response['link'] = NULL;

        echo json_encode($response);
    }
} else if ($_GET['action'] == "announce_upload") {
    if (move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $announce_path)) {
        echo baseUrl() . str_replace('../', '', $announce_path);
    } else {
        $response['status'] = "Error";
        $response['link'] = NULL;

        echo json_encode($response);
    }
} else if ($_GET['action'] == "task_upload") {
    if (move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $task_path)) {
        echo baseUrl() . str_replace('../', '', $task_path);
    } else {
        $response['status'] = "Error";
        $response['link'] = NULL;

        echo json_encode($response);
    }
} else if ($_GET['action'] == "view") {
    $dir = $_GET['folder'] == '' ? opendir(UPLOAD_DIR) : opendir(UPLOAD_DIR . $_GET['folder'] . "/");

    while ($file = readdir($dir)) {
        if ($file == '.' || $file == '..') {
            continue;
        }

        $contents['Content'] = $file;
        $contents['Type'] = is_dir(UPLOAD_DIR . $_GET['folder'] . "/" . $file) ? "Folder" : "File";

        $response[] = $contents;
    }
    echo json_encode($response);
} else {
    echo 'Action not define!';
}
?>